package iws.g5.uebung3.impls;

import java.util.Random;

import iws.g5.uebung3.StateModel;
import iws.g5.uebung3.enums.EventType;
import iws.g5.uebung3.enums.OrganicType;
import iws.g5.uebung3.interfaces.LivingOrganicObject;
import iws.g5.uebung3.interfaces.OrganicObject;

public class Virus extends LivingOrganicObject implements OrganicObject {

	static Random rand = new Random(1);
	int noFoodCount;
	int iteration=0;
	
	public Virus(StateModel env, int birthIteration) {
		super(env, birthIteration);
	}

	@Override
	public OrganicType getType() {
		return OrganicType.VIRUS;
	}

	@Override
	public void onEventTriggered(int iteration, EventType event) {
		if(event==EventType.CELLDIVISION){
			reproduce(iteration);
		}

		if(event==EventType.IMMUNIZATION) {
			if(rand.nextDouble() < 0.95) {
				die();
			}
		}
	}
	
	public void reproduce(int iteration){
		this.iteration = iteration;
		
		if(rand.nextDouble() < 0.15 && tryToFindFood()) {
			noFoodCount = 0;
		} else {
			noFoodCount++;
		}
		
		if(noFoodCount > 12) {
			die();
		}
	}

	private boolean tryToFindFood() {
		for (int x = -1; x <= 1; x++) {
			for (int y = -1; y <=1 ; y++) {
				if(checkFieldForFood(xPosition+x, yPosition+y)) {
					return true;
				}
			}			
		}
		return false;
	}

	private boolean checkFieldForFood(int x, int y) {
		if(x>0 && y>0 && x<env.getXDimension() && y<env.getYDimension() ) {
			OrganicObject object = env.getOrganicObject(x, y);
			if(object != null && object.getType() == (OrganicType.CELL)) {
				env.removeOrganicObject(x, y);
				env.addOrganicObject(new Virus(env, iteration), x, y);
				return true;
			}
		}
		return false;
	}


	public void die() {
		env.removeOrganicObject(xPosition, yPosition);
		env.addOrganicObject(new Food(), xPosition, yPosition);
	}

}
